package com.jiyici;

import java.util.ArrayList;

import android.os.Bundle;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.jiyici.controller.DataManager;
import com.jiyici.model.Item;
import com.jiyici.model.ItemParam;
import com.jiyici.utils.NotificationUtil;
import com.jiyici.utils.StringUtils;
import com.jiyici.view.ItemEditView;

public class EditItemActivity extends SherlockActivity {

    private ItemEditView mItemEditView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        GlobalTheme.applyTheme(this, true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Item item = (Item) getIntent().getSerializableExtra("item");
        getSupportActionBar().setTitle(
                ViewUtil.getTitle(getText(item != null ? R.string.actionbar_item_edit_item
                        : R.string.actionbar_item_new_item)));
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_edit_item);

        mItemEditView = (ItemEditView) findViewById(R.id.itemeditview);

        if (item != null)
            mItemEditView.setItem(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(R.string.actionbar_item_cancel).setShowAsAction(
                MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        menu.add(R.string.actionbar_item_done).setShowAsAction(
                MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId() || getText(R.string.actionbar_item_cancel).equals(item.getTitle())) {
            finish();
            return true;
        } else if (getText(R.string.actionbar_item_done).equals(item.getTitle())) {
            Item myitem = mItemEditView.getItem();
            ArrayList<ItemParam> deletedParams = mItemEditView.getDeletedItemParams();
            if (StringUtils.isBlank(myitem.itemName)) {
                NotificationUtil.notifyError(mItemEditView, R.string.user_error_item_name_empty);
                return true;
            }
            DataManager.saveItem(myitem, deletedParams);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
